<template>
  <div class="app-container">
    <div class="top">
      <div class="top_title">
        <el-input
          class="top_input"
          v-model="form.title"
          placeholder="请输入标题"
          clearable
        />
      </div>

      <div class="top_submit">
        <el-button type="primary" round @click="handleSubmitBefore">发布文章</el-button>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      v-model="articleDialogVisible"
      title="发布文章"
      width="800"
      :before-close="handleArticleClose"
    >
      <el-form :model="form" label-width="auto" style="max-width: 800px">
        <el-form-item label="文章分类">
          <el-tree-select
              v-model="form.categoryId"
              :data="categoryOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              placeholder="选择分类"
              check-strictly
          />
        </el-form-item>
        <el-form-item label="文章标签">
          <el-popover class="tag_container" placement="bottom-start" title="标签" :width="580" trigger="click">
            <template #reference>
              <div>
                <el-tag class="tag_check" v-for="tag in checkedTagList" :key="tag.name" closable :disable-transitions="false" @close="handleTagClose(tag)">
                  {{tag.name}}
                </el-tag>
                <el-button icon="Plus">添加文章标签</el-button>
              </div>
            </template>
            <!-- 输入框 -->
            <el-input placeholder="请输入内容" v-model="tagSearchKeyword" clearable> </el-input>
            <!-- 选项 -->
            <div class="tag_body">
              <div class="tag_left">
                <div class="tag_left_item" :class="[ currentTagIndex == index ? 'left_active':'' ]" v-for="(item,index) in tagOptions" :key="index" @click="handleChangeTag(index,item)">{{ item.name }}</div>
              </div>
              <div class="tag_right">
                <el-tag class="tag_right_item" v-for="(item,index) in tagItemOptions" :key="item" @click="handleChangeTagItem(index,item)">{{ item.name }}</el-tag>
              </div>
            </div>
          </el-popover>
          
        </el-form-item>
        <el-form-item label="添加封面">
          <ImgLocalUpload v-model="form.mainImg" imgType="article"/>
        </el-form-item>
        <el-form-item label="文章摘要">
          <el-input v-model="form.summary" type="textarea" />
        </el-form-item>
        <el-form-item label="文章类型">
          <el-radio-group v-model="form.pushType">
            <el-radio :label="index" v-for="(item,index) in articleTypeOptions" :index="index">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="可见范围">
          <el-radio-group v-model="form.showScope">
            <el-radio :label="index" v-for="(item,index) in articleShowScopeOptions" :index="index">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">发布文章</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 文章编辑区 -->
    <v-md-editor 
      v-model="form.content"
      class="my_editor"
      height="100%"
      :disabled-menus="[]"
      @upload-image="handleUploadImage"
      ></v-md-editor>
  </div>
</template>

<script setup name="amsEdit">
import { addArticle,getArticle,updateArticle } from "@/api/ams/article";
// 导入本地图片上传
import { signLocImgUpload } from '@/api/file/localImage';
import { listCategory } from "@/api/ams/category";
import { listTag } from "@/api/ams/tag";
const router = useRouter();
const route = useRoute();
// 获取文章
const articleId = ref(route.query.id)
const { proxy } = getCurrentInstance();

// 标签搜索
const tagSearchKeyword = ref("");
// 当前选中父标签
const currentTagIndex = ref(0);
// 文章属性
const articleTypeOptions = ref(['原创','转载','翻译'])
const articleShowScopeOptions = ref(['全部可见','VIP可见'])
// 弹窗等变量
const articleDialogVisible = ref(false);
// 文章分类
const categoryOptions = ref([]);
const tagOptions = ref([]);
const tagItemOptions = ref([]);
const tagList = ref([]);
const checkedTagList = ref([]);
const data = reactive({
  form: {
    id: undefined,
    userId: undefined,
    categoryId: undefined,
    title: undefined,
    mainImg: undefined,
    summary: undefined,
    content: undefined,
    readType: 0,
    isStick: 0,
    isPublish: 0,
    pushType: 0,
    showScope: 0,
    originalUrl: undefined,
    quantity: undefined,
    isCarousel: 0,
    isRecommend: 0,
    keywords: undefined,
    checkedTagList: []
  },

  rules: {
  
  }
});

const { form, rules } = toRefs(data);

// 发布文章之前，弹窗选择文章标签，分类
function handleSubmitBefore() {
  getTreeselect();
  getTags();
  articleDialogVisible.value =true;
}
// 发布
function handleSubmit() {
  form.value.checkedTagList = checkedTagList.value.map(item => item.name);
  if(form.value.id) {
    updateArticle(form.value).then(resp => {
      if(resp.code == 200) {
        proxy.$modal.msgSuccess("发布成功");
        articleDialogVisible.value =false;
      }
    })
  }else {
    addArticle(form.value).then(resp => {
      if(resp.code == 200) {
        proxy.$modal.msgSuccess("修改成功");
        articleDialogVisible.value =false;
      }
    })
  }
  reset();
}
// 关闭弹窗
function handleArticleClose() {
  articleDialogVisible.value =false;
}
/** 查询分类下拉树结构 */
function getTreeselect() {
 categoryOptions.value = [];
 listCategory().then(response => {
   const category = { id: 0, name: "主类目", children: [] };
   category.children = proxy.handleTree(response.data, "id");
   categoryOptions.value.push(category);
 });
}
// 获取标签
function getTags() {
  listTag().then(resp => {
    if(resp.code == 200) {
      let data = resp.data;
      currentTagIndex.value = 0;
      tagList.value = data;
      tagOptions.value = data.filter(item => item.parentId == 0);
      tagItemOptions.value = data.filter(item => item.parentId == tagOptions.value[0].id);
    }
  })
}
// 修改标签
function handleChangeTag(index,tag) {
  currentTagIndex.value = index;
  // 联查对应的标签
  tagItemOptions.value = tagList.value.filter(item => item.parentId == tag.id);
}
// 选择标签
function handleChangeTagItem(index,tag) {
  checkedTagList.value.push(tag);

}
// 移除标签
function handleTagClose(tag) {
  checkedTagList.value.splice(checkedTagList.value.indexOf(tag), 1)
}
// 图片上传
function handleUploadImage(event, insertImage, files) {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  let formData = new FormData();
  formData.append("file", files[0]);
  formData.append('imgType', 'acritle')
  // 文件上传
  signLocImgUpload(formData).then(resp => {
    if(resp.code === 200) {
      // 此处只做示例
      insertImage({
        url: resp.data.url,
        desc: resp.data.filename,
        // width: 'auto',
        // height: 'auto',
      });
    }
  })
}

// 格式化表单
function reset() {
  form.value =  {
    id: undefined,
    userId: undefined,
    categoryId: undefined,
    title: undefined,
    mainImg: undefined,
    summary: undefined,
    content: undefined,
    pushType: 0,
    topStatus: 0,
    pushStatus: 0,
    pushType: 0,
    showScope: 0,
    originalUrl: undefined,
    readVolume: undefined,
    isCarousel: 0,
    isRecommend: 0,
    checkedTagList: []
  }
  checkedTagList.value = [];
}
// 初始化文章数据
function initArticle() {
  reset();
  if(articleId.value) {
    // 根据id查询数据
    getArticle(articleId.value).then(resp => {
      if(resp.code === 200) {
        let data = resp.data;
        let tagStr = data.tag;
        
        form.value = data;
        if(tagStr) {
          let tagList = tagStr.split(',');
          for (const item of tagList) {
            checkedTagList.value.push({name: item});
          }
        }
      }
    })
  }
}
initArticle();
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-sizing: border-box;
  margin-bottom: 20px;
  .top_title {
    margin-right: 30px;
    width: 100%;
    .el-input {
      width: 100%;
      .el-input__inner {
        padding: 20px;
      }
    }
  }

  .top_submit {

  }
}
// 标签
.tag_container {
  height: 300px;
  width: 580px;
  padding: 10px 15px;
  border: 1px solid #e3e3e3;
  box-shadow: 0 2px 6px 0 rgba(0,0,0,.1);
}
.tag_check {
  margin-right: 5px;
}
.tag_body {
    display: flex;
    justify-content: flex-start;
    align-items: start;
    box-sizing: border-box;
    width: 100%;
    margin-top: 10px;
    .tag_left {
      width: 150px;
      height: 100%;
      overflow-y: auto;
      margin: 0;
      padding: 0;
      .tag_left_item {
        font-weight: 400;
        cursor: pointer;
        margin-bottom: 6px;
        color: #777888;
        font-size: 14px;
        padding-left: 16px;
      }
    }
    .tag_right {

    }
    .tag_right_item {
      margin-right: 4px;
      cursor: pointer;
    }
  }

  .left_active {
    color: #204f7f !important;
  }
  .v-md-textarea-editor {
    pre {
      min-height: 900px !important;
    }
    
  }
</style>